<script>
import get from 'lodash/get'
import request from '@/utils/request'
export default {
  props: {
    option: {
      type: Object,
      default: () => {}
    },
    form: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      formRules: {},
      defaultFormSize: 'small',
      defaultLabelWidth: '90px',
      defaultLabelHeight: '50px'
    }
  },
  computed: {
    formColumn() {
      return this.option.column
    }
  },
  created() {
    this.initRules()
    this.initRequest()
    this.initValue()
  },
  methods: {
    get,
    getPlaceholder(type, label) {
      return type === 'el-select' ? `请选择${label}` : `请输入${label}`
    },
    initRequest() {
      if (!Array.isArray(this.formColumn)) return
      const urls = this.formColumn?.filter((item) => item.url && item.url.indexOf('/park') === 0) || []
      urls.forEach(async(item) => {
        const params = { ...item.requestParams }
        // 请求的方法和接收的数据，和后台商量来写
        const res = await request({
          url: item.url,
          method: 'get',
          params
        }) || []
        // 整理数据
        const finalResult = res.map((result) => ({
          label: result[item.requestLabel],
          value: result[item.requestValue]
        }))
        // set数据
        this.$set(item, 'dic', finalResult)
      })
    },
    initRules() {
      if (!Array.isArray(this.formColumn)) return
      this.formColumn?.forEach((item) => {
        if (item.rules) {
          item.rules.map((rule, index) => {
            // 生成必填项的校验规则
            if (rule.required) {
              item.rules.splice(index, 1, {
                message: ['el-radio-group', 'el-checkbox-group'].includes(item.type) ? item.label + '必选' : item.label + '必填',
                ...rule
              })
            }
          })
          // 添加校验规则
          this.$set(this.formRules, item.prop, item.rules)
        }
      })
    },
    initValue() {
      const selectList = this.formColumn.filter((item) => ['el-radio-group', 'el-checkbox-group'].includes(item.type))
      // 设置radio和checkbox默认第一个值选中
      selectList.forEach((item) => {
        this.$set(this.form, item.prop, item.type === 'el-radio-group' ? item.dic[0].label : [item.dic[0].value])
      })
    },
    renderFields(column) {
      switch (column.type) {
        case 'el-select':
          return column.dic?.map(item =>
            <el-option
              key={item.value}
              label={item.label}
              value={item.value}
            />
          )
        case 'el-radio-group':
          return column.dic.map(item =>
            <el-radio
              key={item.value}
              label={item.label}
            >
              { item.value }
            </el-radio>
          )
        case 'el-checkbox-group':
          return column.dic.map(item =>
            <el-checkbox
              key={item.label}
              label={item.value}
            >
              { item.label }
            </el-checkbox>
          )
        default:
          break
      }
    },
    renderItem() {
      return this.formColumn.map(column => (
        <el-col
          key={column.label}
          md={column.span || 12}
          sm={12}
          xs={24}
        >
          <el-form-item
            label={column.label ? `${column.label}:` : ''}
            prop={column.prop}
            label-width={get(column, 'labelWidth', column.labelWidth || this.defaultLabelWidth)}
            style={{ height: get(column, 'labelHeight', column.labelHeight || this.defaultLabelHeight) }}
          >
            {column.slotName ? this.$slots[column.slotName]
              : <component
                is={get(column, 'type', 'el-input')}
                vModel={this.form[column.prop]}
                clearable
                style='width: 100%'
                range-separator='-'
                start-placeholder='开始日期'
                end-placeholder='结束日期'
                placeholder={this.getPlaceholder(column.type, column.label)}
                label-width={get(column, 'size', column || this.defaultFormSize)}
                disabled={get(column, 'disabled', false)}
                row={get(column, 'attr.row', 2)}
                type={get(column, 'attr.type', 'daterange')}
              >
                {this.renderFields(column)}
              </component>
            }
          </el-form-item>
        </el-col>
      ))
    }
  },
  render() {
    return (
      <el-form
        ref='form'
        model={this.form}
        rules={this.formRules}
        size={get(this.option, 'formSize', this.defaultFormSize)}
        validate-on-rule-change={false}
        onSubmit={(e) => { e.preventDefault() }}
      >
        <el-row gutter={20} span={24}>
          {this.renderItem()}
        </el-row>
        <slot name='footer' form={this.form} />
      </el-form>
    )
  }
}
</script>
